package com.cs.csboot;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class Spring implements ApplicationContextAware {

	private static final Logger logger = LoggerFactory.getLogger(Spring.class);
    public static AnnotationConfigApplicationContext APP;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(Spring.APP == null) {
            Spring.APP = (AnnotationConfigApplicationContext) applicationContext;
        }
    }
    
    public static void registBean(String beanName,Object object,Class<?> beanClass)
    {
    	 //判断
        if (Spring.APP.containsBeanDefinition(beanName)){
            //如果Spring上下文已存在Bean，先删除
            Spring.APP.removeBeanDefinition(beanName);
        }else{
            //如果不存在，创建
            BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(beanClass);
            Spring.APP.registerBeanDefinition(beanName,builder.getBeanDefinition());
        }

        //注入JdbcTemplate实例
        Spring.APP.getBeanFactory().registerSingleton(beanName,object);

        //打印测试：
        logger.info("set dataSource : "+beanName);
    }

}
